package com.mukefile.dao.impl;

import com.mukefile.dao.SysProfileDao;
import com.mukefile.pojo.ResponseData;
import com.mukefile.pojo.SysProfile;
import com.mukefile.utils.GetPageInfo;
import com.mukefile.utils.PageInfo;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author xinke.huang@hand-china.com
 * @version 1.0
 * @date 2021/2/5
 */
@Repository("SysProfileDao")
public class SysProfileDaoImpl implements SysProfileDao {
    @Autowired
    HibernateTemplate hibernateTemplate;
    @Override
    public int insertSysProfile(SysProfile sysProfile) {
        hibernateTemplate.save(sysProfile);
        return 1;
    }

    @Override
    public int updateSysProfile(SysProfile sysProfile) {
        hibernateTemplate.saveOrUpdate(sysProfile);
        return 1;
    }

    @Override
    public int batchDeleteSysProfile(List<SysProfile> list) {
        hibernateTemplate.deleteAll(list);
        return 1;
    }

    @Override
    public String querySysProfileByName(String profileName) {
        SysProfile sysProfile = new SysProfile();
        sysProfile.setProfileName(profileName);
        List<SysProfile> list = hibernateTemplate.findByExample(sysProfile);
        return (list.isEmpty()? "" : list.get(0).getProfileValue());
    }

    @Override
    public ResponseData<SysProfile> selectProfile(int page, int recPerPage) {
        Session session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        String sql = "select count(id) from sys_profile";
        // 创建PageInfo对象
        PageInfo<SysProfile> pageInfo = new PageInfo<>();
        // 获取limit查询参数
        GetPageInfo<SysProfile> pi  = new GetPageInfo<>();
        pi.limitPage(page-1,recPerPage);
        // 获取总记录数
        Integer count = Integer.parseInt(session.createSQLQuery(sql).list().get(0).toString());
        String sql2 = "select * from sys_profile limit ?,?";
        List list = session.createSQLQuery(sql2)
                .addEntity(SysProfile.class)
                .setParameter(1,pi.getLimitStart())
                .setParameter(2,pi.getLimitEnd()).list();
        return new ResponseData<>(count,list);
    }
}
